import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/components/dialog/exit_tips.dart';
import 'package:enterprise_v6_app/app/components/drawer_title.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/page_base_drawer.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/special_list_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///特殊作业-侧边栏样式
///[executeEntity]流程执行节点实体
///[selectIndex]当前选择项,选中的页面
///[receiptType]作业票作业状态 0：待开票 1：开票中 2：进行中 3：中断 4：已验收
///[scaffoldKey]scaffoldKey
///[titleList]侧边栏按钮
///[onNextStep]下一步
///[selectLeftMenu]点击左侧回调索引
class CustomSidebarView extends StatefulWidget {
  const CustomSidebarView({
    required this.executeEntity,
    required this.selectIndex,
    required this.receiptType,
    required this.scaffoldKey,
    required this.titleList,
    required this.onNextStep,
    required this.selectLeftMenu,
    super.key,
  });

  final ExecuteEntity executeEntity;
  final int selectIndex;
  final int receiptType; //作业票作业状态 0：待开票 1：开票中 2：进行中 3：中断 4：已验收
  final GlobalKey<ScaffoldState> scaffoldKey;
  final List<PageBaseEntity> titleList;
  final Function() onNextStep;
  final Function(int index) selectLeftMenu;

  @override
  State<CustomSidebarView> createState() => _CustomSidebarViewState();
}

class _CustomSidebarViewState extends State<CustomSidebarView> {
  int selectIndex = 0;

  @override
  initState() {
    super.initState();
    selectIndex = widget.selectIndex;
  }

  ///标题显示
  Widget _appBar(
    int? titleIndex,
  ) {
    if (widget.titleList[titleIndex!].pageTitle == null) {
      return Text(widget.titleList[titleIndex].title,
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
          ));
    }
    return Container(
      height: 35.w,
      padding: EdgeInsets.only(left: 16.w, right: 16.w),
      child: Container(
        width: 84.w * widget.titleList[titleIndex].pageTitle!.length,
        decoration: BoxDecoration(
          color: const Color(0x1F5C6DFF),
          border: Border.all(
            color: const Color(0xff5C6DFF),
            width: 1.w,
          ),
          borderRadius: BorderRadius.circular(4.r),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: widget.titleList[titleIndex].pageTitle!.map((e) {
            final bool isCurrent =
                widget.titleList[titleIndex].pageTitle?.indexOf(e) ==
                    widget.titleList[titleIndex].currentPageTitle;
            return Container(
              width: 81.w,
              height: 28.w,
              decoration: BoxDecoration(
                color: isCurrent ? const Color(0xff5C6DFF) : null,
                borderRadius: BorderRadius.circular(3.r),
              ),
              alignment: Alignment.center,
              child: Text(
                e,
                style: TextStyle(
                    fontSize: 14.sp,
                    color: isCurrent ? Colors.white : const Color(0xff5C6DFF),
                    fontWeight: FontWeight.w500),
              ),
            ).click(() {
              selectTitle(titleIndex,
                  widget.titleList[titleIndex].pageTitle!.indexOf(e));
            });
          }).toList(),
        ),
      ),
    );
  }

  /// 点击右侧菜单
  ///  [name] 名称
  void jumpToPage(String name) {
    switch (name) {
      case '详情':
        Get.toNamed(AppRoutes.workDetailAll,
            arguments: widget.executeEntity.ticketReceiptId);
        break;
      case '作业票':
        // Get.toNamed(AppRoutes.fireWorkTicketAll);
        break;
    }
  }

  /// 右侧页面选择菜单
  List<String> rightMenuList = [
    // '详情',
    // '作业票',
  ];

  ///右侧按钮
  Widget _action() {
    return Container(
        margin: EdgeInsets.only(right: 16.w),
        child: DropdownButtonHideUnderline(
            child: DropdownButton2<String>(
          items: rightMenuList.map((item) {
            return DropdownMenuItem<String>(
              value: item,
              child: Container(
                alignment: Alignment.centerLeft,
                child: Text(
                  item,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  style: TextStyle(
                    fontSize: 18.w,
                    fontWeight: FontWeight.w400,
                    color: const Color(0xffFFFFFF),
                  ),
                ),
              ),
            );
          }).toList(),
          //选择框样式
          dropdownStyleData: DropdownStyleData(
            width: 100.w,
            padding: EdgeInsets.symmetric(vertical: 10.w),
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.0),
                  spreadRadius: 0,
                  blurRadius: 0,
                ),
              ],
              borderRadius: BorderRadius.circular(4.w),
              color: const Color(0xff434343),
            ),
            offset: const Offset(-60, 0),
          ),
          customButton: Icon(
            Icons.reorder,
            size: 25.w,
            color: const Color(0xff495061),
          ),
          onChanged: (value) {
            jumpToPage(value!);
          },
        )));
  }

  /// title选择切换
  /// [titleIndex] 标题索引
  /// [index] 页面索引
  void selectTitle(int titleIndex, int index) {
    widget.titleList[titleIndex].currentPageTitle = index;
    setState(() {});
  }

  /// 点击展开菜单
  /// [index] 索引
  void selectExpandMenu(int index) {
    Get.back();
    setState(() {});
  }

  /// 点击左侧菜单
  /// [index] 索引
  void selectLeftMenu(int index) {
    if (widget.selectIndex != index) {
      if (widget.receiptType == 1 || widget.receiptType == 2) {
        Get.dialog<bool>(ExitTips(
          content: '切换节点后所填信息不支持继续编辑，是否继续？',
          func: (v) {
            if (v) {
              widget.selectLeftMenu(index);
              setState(() {});
            }
          },
        ));
      } else {
        widget.selectLeftMenu(index);
        setState(() {});
      }
    }
  }

  ///判断右侧按钮显示
  void initRightMenu() {
    //开票中
    if (widget.receiptType != 2) {
      rightMenuList = [
        '详情',
        '作业票',
      ];
    } else {
      rightMenuList = ['详情', '作业票', '管理'];
    }
  }

  /// 撤销作业票
  void revokeTicketReceipt() {
    Get.dialog<bool>(
      ExitTips(
        content: '是否确认撤销当前作业票？',
        func: (v) async {
          if (v) {
            //获取数据
            final res = await HttpUtil().generateGetRequest(
                Interface.revokeTicketReceipt,
                queryParameters: {
                  'ticketReceiptId': widget.executeEntity.ticketReceiptId
                }).execute();
            res.onSuccess((result) {
              //外部列表controller
              final specialListController = Get.find<SpecialListController>();
              specialListController.refreshPage();
              //关闭当前页面
              Get.back();
              AppToast.showSuccess('撤销成功');
            });
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    initRightMenu();
    return Scaffold(
        appBar: CustomAppBar(
          title: _appBar(widget.selectIndex),
          actions: [
            _action(),
          ],
        ),
        body: Scaffold(
          key: widget.scaffoldKey,
          drawer: Drawer(
              width: 200.w,
              child: Container(
                color: Colors.white,
                child: Column(
                  children: [
                    DrawerTitle.titleDrawer('收起', AppImages.icon_pack_up)
                        .click(() {
                      widget.scaffoldKey.currentState?.closeDrawer();
                    }),
                    Column(
                      children: widget.titleList.map((e) {
                        return DrawerTitle.titleDrawer(e.title, e.icon,
                                isSelected: widget.selectIndex ==
                                    widget.titleList.indexOf(e))
                            .click(() {
                          selectExpandMenu(widget.titleList.indexOf(e));
                          selectLeftMenu(widget.titleList.indexOf(e));
                        });
                      }).toList(),
                    ),
                  ],
                ),
              )),
          body: Row(
            children: [
              Container(
                width: 60.w,
                color: Colors.white,
                alignment: Alignment.topCenter,
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      DrawerTitle.title('展开', AppImages.icon_launch).click(() {
                        widget.scaffoldKey.currentState?.openDrawer();
                      }),
                      Column(
                        children: widget.titleList.map((e) {
                          return DrawerTitle.title(e.title, e.icon,
                                  isSelected: widget.selectIndex ==
                                      widget.titleList.indexOf(e))
                              .click(() {
                            selectLeftMenu(widget.titleList.indexOf(e));
                          });
                        }).toList(),
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                child: widget.titleList[widget.selectIndex].pages[
                    widget.titleList[widget.selectIndex].currentPageTitle],
              ),
            ],
          ),
          bottomSheet: Visibility(
              // visible: true,
              //开票中和进行中的才显示按钮
              visible: widget.receiptType == 1 || widget.receiptType == 2,
              child: Container(
                width: double.infinity,
                color: Colors.white,
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 5.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    SizedBox(
                      width: 120.w,
                      height: 40.w,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                              backgroundColor: const Color(0xffFFFFFF),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(22.r),
                              ),
                              side: BorderSide(
                                color: const Color(0xff5C6DFF),
                                width: 1.w, // 设置边框线的宽度
                              )),
                          onPressed: revokeTicketReceipt,
                          child: Text(
                            '撤销',
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: const Color(0xff5C6DFF),
                            ),
                          )),
                    ),
                    SizedBox(
                      width: 200.w,
                      height: 40.w,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: AppColors.blue_button,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(22.r),
                            ),
                          ),
                          onPressed: widget.onNextStep,
                          child: Text(
                            '下一步',
                            style: TextStyle(
                              fontSize: 16.sp,
                              color: Colors.white,
                            ),
                          )),
                    ),
                  ],
                ),
              )),
        ));
  }
}
